//
//  SendTopicViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/2/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import ImagePicker
import UITableView_FDTemplateLayoutCell
import SVProgressHUD
import TZImagePickerController
import AVOSCloud

let kNotificationNameKeybordDown = "kNotificationNameKeybordDown" // 收键盘通知


class SendTopicViewController: RootViewController, ImagePickerDelegate, UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate {
    
    var city: City?
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewBottom: NSLayoutConstraint!
    
    var imagePickerController:ImagePickerController?
    var imageArray = [UIImage]() // 弃用
    var topicTitle = ""
    var topicContent = ""
    var addButtonCell: SendAddButtonsCell?
   
    var selectedPhotos = [UIImage]()
    var selectedAssets = [AnyObject]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "发布话题"
        
        tableView.tableFooterView = UIView()
        view.backgroundColor = tableView.backgroundColor
    }
    
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(SendTopicViewController.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
         NotificationCenter.default.addObserver(self, selector: #selector(SendTopicViewController.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self)
    }
   
    @IBAction func topicSend(_ sender: UIBarButtonItem) {
        SVProgressHUD.show(withStatus: "数据提交中...")
         NotificationCenter.default.post(name: Notification.Name(rawValue: kNotificationNameKeybordDown), object: nil) // 收键盘
        if topicTitle.isEmpty || topicTitle.characters.count < 3 {
            SVProgressHUD.showError(withStatus: "请输入主题: 3-30字")
            return
        } else if topicContent.isEmpty || topicContent.characters.count < 3 {
            SVProgressHUD.showError(withStatus: "请输入内容: 3-1000字")
            return
        }
        var fileArray = [AVFile]()
        
        for img in selectedPhotos {
//            let data = UIImagePNGRepresentation(img)
            let data = UIImageJPEGRepresentation(img, 0.7)
            let file = AVFile(data: data!)
            fileArray.append(file)
        }
        
        let topic = Topic()
        topic.user = AVUser.current()
        topic.title = topicTitle
        topic.content = topicContent
        topic.contentImage = fileArray
        topic.clickCount = 1
        topic.replyCount = 0
        topic.isInTop = false
        topic.isDelete = false
        topic.isCommend = false
        topic.city = city
        topic.lastReplyTime = Date()
        topic.userName = AVUser.current().username
        
        topic.saveInBackground { (succed: Bool, error: Error?) in
            if succed {
                self.city?.incrementKey(kCityKeyTopicCount)
                self.city?.fetchWhenSave = true
//                self.city?.saveInBackground()
                
                let user = AVUser.current()
                user.incrementKey(kUserKeySendCount)
                user.fetchWhenSave = true
                
                AVObject.saveAll(inBackground: [self.city!, user]) // 批量update和save
                
                self.navigationController?.popViewController(animated: true)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotificationRefreshCircleListView), object: nil)
                SVProgressHUD.showSuccess(withStatus: "提交成功")
            } else {
                SVProgressHUD.showSuccess(withStatus: error?.localizedDescription)
            }
        }
    }
    
    func presentImagePicker() {
        
//        if self.imagePickerController == nil {
//            self.imagePickerController = ImagePickerController()
//            self.imagePickerController?.delegate = self
//            self.imagePickerController?.imageLimit = 3
//        }
//        dispatch_async(dispatch_get_main_queue(), {
//            self.presentViewController(self.imagePickerController!, animated: true, completion: nil)
//        })
        
        let imagePickerVc = TZImagePickerController(maxImagesCount: 3, delegate: self)
        
        imagePickerVc?.selectedAssets = NSMutableArray(array: selectedAssets)
        imagePickerVc?.allowPickingVideo = false
        imagePickerVc?.allowPickingOriginalPhoto = false
        
        self.present(imagePickerVc!, animated: true) {}
    }
    
     // MARK: TZImagePickerControllerDelegate
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [AnyObject]!, isSelectOriginalPhoto: Bool) {
        selectedPhotos = photos
        selectedAssets = assets
        self.addButtonCell?.refreshButtons(selectedPhotos)
    }
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [AnyObject]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable: Any]]!) {
        
    }
    
    func imagePickerControllerDidCancel(_ picker: TZImagePickerController!) {
        
    }
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: AnyObject!) {
        
    }
    
    
    @IBAction func tapGesture(_ sender: UITapGestureRecognizer) {
        NotificationCenter.default.post(name: Notification.Name(rawValue: kNotificationNameKeybordDown), object: nil) // 收键盘
    }
    
    // MARK: ImagePickerDelegate
    func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
        
    }
    func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
        imagePickerController?.dismiss(animated: true, completion: nil)
        imageArray = images
        self.addButtonCell?.refreshButtons(images)
    }
    func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
        
    }
    
    // MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath as NSIndexPath).row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SendTitleTextFieldCell", for: indexPath) as! SendTitleTextFieldCell
            cell.selectionStyle = .none
            cell.setBlock({ (text: String) in
                self.topicTitle = text
            })
            return cell
        } else if (indexPath as NSIndexPath).row == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SendContentTextViewCell", for: indexPath) as! SendContentTextViewCell
            cell.selectionStyle = .none
            cell.setBlock({ (text: String) in
                self.topicContent = text
            })
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SendAddButtonsCell", for: indexPath) as! SendAddButtonsCell
            cell.selectionStyle = .none
            cell.setBlock({ (sender: UIButton) in
                self.presentImagePicker()
            })
            self.addButtonCell = cell
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath as NSIndexPath).row == 0 {
            return 44
        } else if (indexPath as NSIndexPath).row == 1 {
            return 140
        } else {
           return (UIScreen.main.bounds.width-8*4)/3+2
        }
    }
    
    // MARK: NSNotificationCenter
    
    func keyboardDidShow(_ noti: Notification) {
        
        let keyBordHeight = ((noti as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height
        tableViewBottom.constant = keyBordHeight
    }
    
    func keyboardDidHide(_ noti: Notification) {
        
        UIView.animate(withDuration: 0.1, animations: {
            self.tableViewBottom.constant = 0
            self.tableView.layoutIfNeeded()
        }) 
    }
    
}


typealias sendValueClosure = (_ text:String)->Void
typealias addButtonClosure = (_ sender:UIButton)->Void

class SendTitleTextFieldCell: UITableViewCell, UITextFieldDelegate {
    
    @IBOutlet weak var titleTextField: UITextField!
    
    var myClosure:sendValueClosure?

    override func awakeFromNib() {
        super.awakeFromNib()
        NotificationCenter.default.addObserver(self, selector: #selector(SendTitleTextFieldCell.keybordDown(_:)), name: NSNotification.Name(rawValue: kNotificationNameKeybordDown), object: nil)
        
    }
    
    func setBlock(_ textClosure: @escaping sendValueClosure) {
        myClosure = textClosure
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if (textField.text?.characters.count)! + string.characters.count > 30 {
            SVProgressHUD.showError(withStatus: "最多输入30个字")
            return false
        }
        return true
    }
    
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        myClosure!(textField.text!)
    }
    
    func keybordDown(_ noti:Notification) {
        titleTextField.resignFirstResponder()
    }
    
    deinit {
        //记得移除通知监听
        NotificationCenter.default.removeObserver(self)
    }
}

class SendContentTextViewCell: UITableViewCell, UITextViewDelegate {
    
    @IBOutlet weak var contentTextView: UITextView!
    
    var myClosure:sendValueClosure?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        contentTextView.placeholder = "内容: 3-1000个字"
        NotificationCenter.default.addObserver(self, selector: #selector(SendContentTextViewCell.keybordDown(_:)), name: NSNotification.Name(rawValue: kNotificationNameKeybordDown), object: nil)
    }
    
    func setBlock(_ textClosure: @escaping sendValueClosure) {
        myClosure = textClosure
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        myClosure!(textView.text!)
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if textView.text.characters.count + text.characters.count > 1000 {
            SVProgressHUD.showError(withStatus: "最多输入1000个字")
            return false
        }
        return true
    }
    
    func keybordDown(_ noti:Notification) {
        contentTextView.resignFirstResponder()
    }
    
    deinit {
        //记得移除通知监听
        NotificationCenter.default.removeObserver(self)
    }
}

class SendAddButtonsCell: UITableViewCell {
    
    @IBOutlet weak var addButton1: UIButton!
    @IBOutlet weak var addButton2: UIButton!
    @IBOutlet weak var addButton3: UIButton!
    
    var myClosure:addButtonClosure?
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    @IBAction func addClicked(_ sender: UIButton) {
        myClosure!(sender)
    }
    
    func setBlock(_ textClosure: @escaping addButtonClosure) {
        myClosure = textClosure
    }
    
    func refreshButtons(_ images: [UIImage]) {
        var buttonArray = [addButton1, addButton2, addButton3]
        var i = 0
        
        for image in images {
            let button = buttonArray[i]
            button?.setBackgroundImage(image, for: UIControlState())
            i+=1
        }
        
        buttonArray.removeSubrange(Range(0..<i))
        for button in buttonArray {
            button?.setBackgroundImage(UIImage(named: "sent_add"), for: UIControlState())
        }
    }
}


